package com.rpcdemo.netyyrpc;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * create by yongli on 2021-10-23 16:58
 * Handler和Context 是一一对应
 */

public class EchoClientChannelHandler extends SimpleChannelInboundHandler<ByteBuf> {

    // 先read，后read0
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("it from client read");
        super.channelRead(ctx, msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        System.out.println("it from client read0");
        System.out.println(byteBuf.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        ctx.write("I from client");
        // 不能使用其他的Object，要使用ByteBuf写入
        ctx.writeAndFlush(Unpooled.copiedBuffer("我来自客户端", CharsetUtil.UTF_8));
        System.out.println("channel active");
    }
}
